import React from 'react';
import { Sortable } from 'zent';
import {
    Button,Divider,Popconfirm, message,
    Table, Badge, Menu, Dropdown, Icon, Collapse, Row, Col, Spin
} from 'antd';
import styles from './demo.less';
import { connect } from 'dva';
import OneType from './oneType';
import SecondType from './secondType';
import OneTypeEdit from './oneTypeEdit';

const activeKey =[];

@connect(({ global, productClassify}) => ({
    oemInfo: global.oemInfo,
    productClassify:productClassify.productClassify,
    productFirstGroup: productClassify.productFirstGroup,
  }))

class ProductClassify extends React.Component {
    constructor(props) {
        super(props);
        this.state ={
              loading: true,
              isShowArr: [],
              productClassify: [],
              destory:false,
              dragble: true
        }
    }

    componentWillMount() {
        this.GetGroupList();
        window.Isoption = false;
    }
      componentDidMount() {
        window.Isoption = true;
      }

    handleDelete = id => {
        this.delFirstGroup(id);
    }

    handleSecondDelete = id => {
        this.delSecondGroup(id);
    }

        // 获取全部数据
        GetGroupList = () => {
        const { dispatch} = this.props;
        dispatch({
            type: 'productClassify/GetGroupListWithPage',
            callBack: {
                success: res => {
                    if(res.Code ===0) {                        
                        this.setState({
                            loading: false,
                            productClassify: res.Data,
                            destory:false
                        },()=>{
                            this.forceUpdate();
                        });
                    }
                },
                error: res => {
                    message.error(res.Msg);
                },
            },
        })
        }

        //删除一级
        delFirstGroup = id => {
          const { dispatch } = this.props;
          dispatch({
              type: 'productClassify/DelFirstGroup',
              payload: {
                  id: id,
              },
              callBack: {
                  success: res => {
                      if(res.Code === 0) {
                          message.success('删除成功');
                          this.setState(
                              {
                                  loading: true,
                              },
                              () => {
                                  this.GetGroupList();
                              }
                          );
                      }
                  },
                  error: res => {
                      message.error(res.Msg, 2);
                  },
              }
          })
        }

        referchData = (firstId) => { //更新二级添加
            let indexItem = activeKey.findIndex(item => item===firstId);
            if(indexItem>=0) {
                this.GetGroupList(); 
            } else {
                this.setState({               
                }, ()=> {
                    activeKey.push(firstId);
                    this.setState({
                        isShowArr: activeKey,
                    })
                    this.GetGroupList(); 
                })
            }
        }

        referchNoLoading =() => {
            this.GetGroupList()
        }
  
      //删除二级
      delSecondGroup = id => {
        const { dispatch } = this.props;
        dispatch({
            type: 'productClassify/DelSecondGroup',
            payload: {
                id: id,
            },
            callBack: {
                success: res => {
                    if(res.Code === 0) {
                        message.success('删除成功');
                        this.setState(
                            {
                                loading: true,
                            },
                            () => {
                                this.GetGroupList();
                            }
                        );
                    }
                },
                error: res => {
                    message.error(res.Msg, 2);
                },
            }
        })
      }

      // 二级排序
      changeSecondGroupSort =(id, otherId) => {
        const { dispatch} = this.props;
        dispatch({
            type: 'productClassify/ChangeSecondGroupSort',
            payload: {
                id: id,
                otherId: otherId
            },
            callBack: {
              success: res => {
                if(res.Code === 0) {
                  message.success('排序已更新');
                  this.setState({
                      dragble: true
                  })
                }
              }
            }
        });
        this.forceUpdate()
     }

     // 一级排序
     changeFirstGroupSort =(id, otherId) => {
        const { dispatch} = this.props;
        this.setState({
            loading:true
        })      
        dispatch({
            type: 'productClassify/ChangeFirstGroupSort',
            payload: {
                id: id,
                otherId: otherId
            },
            callBack: {
              success: res => {
                if(res.Code === 0) {
                  message.success('排序已更新');
                 this.setState({
                     destory:true
                 })
                  this.GetGroupList();                 
                }
              }
            }
        });
        // this.forceUpdate()
     }


    // 点击折叠头部
    clickHeader = (Id) => {
        let indexItem = activeKey.findIndex(item => item===Id);
        if(indexItem> -1) {
            activeKey.splice(indexItem, 1);
        }else{
            activeKey.push(Id);
        }
        this.setState({
            isShowArr: activeKey,
        })
    }

    // //折叠全部
    // unShowAll =() => {
    //     this.setState({
    //         isShowArr: []
    //     })
    // }

    // 二层拖拽
    handleSecondChange = (items, index) => {
        const {productClassify } = this.state;
        if(productClassify[index].SecondList.length> 1) {
          const oldId = productClassify[index].SecondList[this.state.oldIndex].Id;
          const newId = productClassify[index].SecondList[this.state.newIndex].Id;
          productClassify[index].SecondList=items;
          this.setState({
              productClassify,
              dragble: false
          },()=>{
              this.forceUpdate();
          });
          this.changeSecondGroupSort(oldId, newId);
        }
    }

    // 第一层拖拽
    handleFirstChange =(items) => {
      const { firstOldIndex, firstNewIndex} = this.state;
      if (this.state.productClassify.length> 1) {
        const oldId = this.state.productClassify[firstOldIndex].Id;
        const newId = this.state.productClassify[firstNewIndex].Id;
        this.changeFirstGroupSort(oldId, newId);
      }}

    render() {
        const { oemInfo ,productClassify} = this.props;
        const {  isShowArr, BannerUrl, loading} = this.state;
      return (
          <div className={styles.contentBox}>
          <Spin spinning={loading}>
            <div style={{marginBottom: 16}}>
                <Button
                    type="primary"
                    style={{marginRight: 8}}
                    onClick={() => {
                        const title = '新增一级分类';
                        this.firstType.show({oemInfo, title}, this.GetGroupList);
                    }}
                >
                    新增一级分类
                </Button>
                {/* <Button onClick={this.unShowAll}>折叠全部</Button> */}
            </div>
                {!this.state.destory?
                <Sortable
                // onChange={this.handleFirstChange}
                // items={[]}
                    onUpdate ={e=> {
                        this.setState({
                        firstOldIndex: e.oldIndex,
                        firstNewIndex: e.newIndex
                    },()=>{
                        const oldId = this.props.productClassify[e.oldIndex].Id;
                        const newId = this.props.productClassify[e.newIndex].Id;
                        this.changeFirstGroupSort(oldId, newId);
                    })
                }}
                    filterClass="demo-sortable-add"
                    dragClass="demo-sortable-drag"
                >
                    {
                        productClassify && productClassify.map((data ,index ) =>{
                            const firstId = data.Id;
                            const firstName = data.Name;
                            const {oemInfo} = this.props;
                            return (
                                <div key={index} className={styles.mainBox}>
                                    <div className={styles.header} onClick={() => this.clickHeader(firstId)}>
                                        <div>
                                        {isShowArr.findIndex(item => item===data.Id)>= 0?
                                            <Icon type="minus-square" style={{color: 'rgba(0,0,0, .3)',cursor: 'pointer'}}/>:
                                            <Icon type="plus-square" style={{color: 'rgba(0,0,0, .3)', cursor: 'pointer'}} />
                                        }
                                        <span style={{marginLeft: 16}}>{data.Name}</span>
                                        </div>
                                        <div style={{fontSize: 14}}>
                                            <a  href="javascript:;"
                                                onClick={(e) => {
                                                e.stopPropagation();
                                                const title = '新增二级分类';
                                                this.secondType.show({action: 'addSecondType',oemInfo, firstName, firstId, title}, this.referchData)
                                            }}>
                                                新增二级分类
                                            </a>
                                            <Divider type="vertical" />
                                            <a href="javascript:;"
                                                onClick={(e) => {
                                                e.stopPropagation();
                                                const title = '编辑一级分类';
                                                this.firstTypeEdit.show({action: 'editType', oemInfo, firstName, firstId, title}, this.referchNoLoading)
                                            }}>
                                                编辑
                                            </a>
                                            <Divider type="vertical" />
                                            <Popconfirm
                                                placement="topRight"
                                                title={(
                                                    <div>
                                                        确定删除?<br/>
                                                        删除一级分类会同时删除其所有二级分类。
                                                    </div>
                                                )}
                                                okText="确认"
                                                cancelText="取消"
                                                onConfirm={e => {
                                                    e.stopPropagation();
                                                    this.handleDelete(firstId)
                                                }}
                                                onCancel={e=> {
                                                    e.stopPropagation();
                                                }}
                                            >
                                                <a href="javascript:;" onClick={e => {e.stopPropagation();}}>删除</a>
                                            </Popconfirm>
                                        </div>
                                    </div>
                                    <Sortable
                                        items={data.SecondList}
                                        onChange={(value) => this.handleSecondChange(value, index)}
                                        sort={this.state.dragble}
                                        onUpdate ={e=> {
                                            this.setState({
                                                oldIndex: e.oldIndex,
                                                newIndex: e.newIndex
                                            })
                                        }}
                                    >
                                        {data.SecondList && data.SecondList.map((v, i)=> {
                                            const secondId = v.Id;
                                            const imageUrl = v.ImgPath;
                                            let secondName = v.Name;
                                            return (
                                                <Row key={secondId} className={styles.secondItem} style={isShowArr.findIndex(item => item===data.Id)>= 0? {display: 'block'}: {display: 'none'}}>
                                                    <Col span={6} className={styles.col}>
                                                        <img
                                                        src={this.props.oemInfo['cdnUrl'] + '/' + v.ImgPath +'?x-oss-process=style/240'}
                                                        width={30}
                                                        height={30}
                                                        />
                                                        <span style={{marginLeft: 16}}>{secondName}</span>
                                                    </Col>
                                                    <Col span={12} style={{textAlign: 'center'}}>商品数量: {v.ProductNum}</Col>
                                                    <Col span={6} style={{textAlign: 'right'}}>
                                                        <a href="javascript:;"
                                                            onClick ={() => {
                                                            const title = '编辑二级分类';
                                                            this.secondType.show(
                                                            {action: 'editType',oemInfo, title, firstId,firstName,secondId, imageUrl, secondName}, this.referchNoLoading);
                                                        }}>
                                                            编辑
                                                        </a>
                                                        <Divider type="vertical" />
                                                        <Popconfirm
                                                            placement="topRight"
                                                            title="确认删除?"
                                                            okText="确认" cancelText="取消"
                                                            onConfirm={() => this.handleSecondDelete(v.Id)}
                                                        >
                                                            <a href="javascript:;">删除</a>
                                                        </Popconfirm>
                                                    </Col>
                                            </Row>
                                            )
                                        })}
                                    </Sortable>
                                </div>
                            );
                        })
                    }
                </Sortable>: <div style={{height: 504}}/>
              }
            </Spin>
            <OneType
                ref={e => {
                    this.firstType = e;
                }}
            />
             <OneTypeEdit
                ref={e => {
                    this.firstTypeEdit = e;
                }}
            />
            <SecondType
                ref= { e=> {
                    this.secondType = e;
                }}
            />
          </div>

      );
    }
}

export default ProductClassify;
